import 'package:flustars/flustars.dart';

import '../app_constants.dart';

///阿姨端网络请求的一些辅助类和数据封装类
class NetHelp{
  static getBaseMap(Map map) {
    var lastMap = new Map<String, dynamic>();
    String time = DateUtil.formatDateMs(DateUtil.getNowDateMs(),format: DateFormats.full);
    lastMap["appid"] = AppConstants.APPID;
    String accessHead = time + AppConstants.APPID + AppConstants.ACCESSKEY;
    lastMap["accesskey"] = getAccess(accessHead: accessHead, map: map??Map());
    lastMap["accesstime"] = time;
    if(ObjectUtil.isEmptyMap(map)){
      return lastMap;
    }else{
      lastMap.addAll(map);
      lastMap.forEach((key, value) {
        if(key!="appid"&&key!="accesskey"){
          print(key + "---------" + value.toString());
        }
      });
      return lastMap;
    }

  }

  static String getAccess({String accessHead, Map map}) {
    if(ObjectUtil.isEmptyMap(map)){
      String accessStr = accessHead;
      return EncryptUtil.encodeMd5(accessStr);
    }else{

      List<String> keys = map.keys.toList();
      // key排序
      keys.sort((a, b) {
        List<int> al = a.codeUnits;
        List<int> bl = b.codeUnits;
        for (int i = 0; i < al.length; i++) {
          if (bl.length <= i) return 1;
          if (al[i] > bl[i]) {
            return 1;
          } else if (al[i] < bl[i]) return -1;
        }
        return 0;
      });
      String accessStr = accessHead;
      keys.forEach((str) {
        if("accesstoken"!=str){//不要accesstoken
          accessStr += str;
        }
      });

      return EncryptUtil.encodeMd5(accessStr);
    }

  }
}


///错误编码
class Code {
  ///网络错误
  static const NETWORK_ERROR = -1;

  ///网络超时
  static const NETWORK_TIMEOUT = -2;

  ///网络返回数据格式化一次
  static const NETWORK_JSON_EXCEPTION = -3;

  static const SUCCESS = 200;

  static errorHandleFunction(code, message, noTip) {
    if(noTip) {
      return message;
    }
//    eventBus.fire(new HttpErrorEvent(code, message));
    return message;
  }
}



class ResultData {
  var data;
  var statusCode;
  var code;
  var headers;
  bool isSuccess;
  String get message =>data["m"]??"no_message";
  String get r =>data["r"]??"99";
  ResultData({this.data, this.code, this.statusCode, this.headers,this.isSuccess}){
    print("data----------------"+data.toString());
    print("code----------------"+code.toString());
    print("statusCode----------"+statusCode.toString());
    print("isSuccess-----------"+isSuccess.toString());
  }

}